package com.ice.bootpack;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.twdata.maven.mojoexecutor.MojoExecutor;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangrenbin
 * @description: springboot jar 及资源文件外置打包插件
 * @date 2022/1/14 001410:15
 */
@Mojo(name = "pack", defaultPhase= LifecyclePhase.PACKAGE)
public class BootPackMojo extends AbstractMojo {

    // 项目的构建路径，一般是/target
    @Parameter(defaultValue = "${project.build.directory}")
    private String buildPath;

    // 项目的名称
    @Parameter(defaultValue = "${project}")
    private MavenProject mavenProject;

    // maven-ssession
    @Parameter(defaultValue = "${session}")
    private MavenSession mavenSession;

    // 注入BuildPluginManager实例
    @Component(role = BuildPluginManager.class)
    private BuildPluginManager buildPluginManager;

    // 插件配置的主类（入口类）
    @Parameter
    private String mainClass;

    @Parameter(defaultValue = "${project.artifactId}")
    private String appName;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("-------begin bootpack-------------");
        //创建assemble文件夹的内容复制到项目工程的target目录
        copyAssesmble();

        // 执行assembly插件
        doAssemble();

        getLog().info("-------end bootpack-------------");

    }

    /**
     * @description: 执行打包
     * @param
     * @return void
     * @throws
     * @author zhangrb
     * @date 2022/1/14 0014
     */
    private void doAssemble() throws MojoExecutionException {
        List<MojoExecutor.Element> configs = new ArrayList<>();
        MojoExecutor.Element[] descriptors = new MojoExecutor.Element[] {
                MojoExecutor.element("descriptor", buildPath + "/assemble/assembly.xml")
        };
        configs.add(MojoExecutor.element("descriptors", descriptors));

        Plugin plugin = MojoExecutor.plugin("org.apache.maven.plugins", "maven-assembly-plugin", "2.6");
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        mavenSession.getUserProperties().setProperty("build-time", timestamp);
        mavenSession.getUserProperties().setProperty("build-path", buildPath);
        // 用此变量替换boot.sh中的MAIN_CLASS
        mavenSession.getCurrentProject().getProperties().setProperty("main-class", mainClass);
        mavenSession.getCurrentProject().getProperties().setProperty("app-name", appName);
        // 执行assembly插件
        MojoExecutor.executeMojo(plugin, "single", MojoExecutor.configuration(configs.toArray(new MojoExecutor.Element[0])),
                MojoExecutor.executionEnvironment(mavenProject, mavenSession, buildPluginManager));
        getLog().info("doAssemble---------finished-----------");
    }

    /**
     * @description: 复制素材
     * @param
     * @return void
     * @throws
     * @author zhangrb
     * @date 2022/1/14 0014
     */
    private void copyAssesmble() throws MojoExecutionException {
        List<MojoExecutor.Element> configs = new ArrayList<>();
        List<MojoExecutor.Element> artifactItems = new ArrayList<>();
        MojoExecutor.Element[] item = new MojoExecutor.Element[] {
                MojoExecutor.element("groupId", getMyGroup()),
                MojoExecutor.element("artifactId", getMyArtifact()),
                MojoExecutor.element("version", getMyVersion()),
                MojoExecutor.element("outputDirectory", buildPath),
                MojoExecutor.element("includes", "bin/*,assemble/*"),
        };

        artifactItems.add(MojoExecutor.element("artifactItem", item));
        configs.add(MojoExecutor.element("artifactItems", artifactItems.toArray(new MojoExecutor.Element[0])));
        Plugin dependencyPlugin = MojoExecutor.plugin("org.apache.maven.plugins", "maven-dependency-plugin", "2.2");

        MojoExecutor.executeMojo(dependencyPlugin, "unpack", MojoExecutor.configuration(configs.toArray(new MojoExecutor.Element[0])),
                MojoExecutor.executionEnvironment(mavenProject, mavenSession, buildPluginManager));
        getLog().info("copyAssesmble---------finished-----------");
    }

    private String getMyVersion() {
        PluginDescriptor pd = (PluginDescriptor)getPluginContext().get("pluginDescriptor");
        return pd.getVersion();
    }

    private String getMyArtifact() {
        PluginDescriptor pd = (PluginDescriptor)getPluginContext().get("pluginDescriptor");
        return pd.getArtifactId();
    }

    private String getMyGroup() {
        PluginDescriptor pd = (PluginDescriptor)getPluginContext().get("pluginDescriptor");
        return pd.getGroupId();
    }
}
